const cheerio = require("cheerio");
const TurndownService = require("turndown");
const {
  Handler,
  CodeHandler,
  TableHandler,
  ListHandler,
  TextHandler,
} = require("./handler");

module.exports = {
  htmlToMarkdown(note) {
    let handlers = [
      new CodeHandler(),
      new TableHandler(),
      new ListHandler(),
      new TextHandler(),
    ];
    // 加标记
    for (let i = 0; i < handlers.length; i++) {
      note = handlers[i].addTag(note);
    }

    // 解析html
    const $ = cheerio.load(note);
    // 获取标题
    let title = $("body > a > h1").text();
    title = title ? title : "";
    let tag = $(
      "body > a > div:nth-child(2) > table > tbody > tr > td:nth-child(2) > i"
    ).text();
    tag = tag ? tag : "";
    // 修改code
    for (let i = 0; i < handlers.length; i++) {
      note = handlers[i].resolveElement($);
    }

    // 获取笔记内容
    let content = $("body > a > div > span");
    if (content.length == 0) {
      content = $("body > div");
    }
    let turndownService = new TurndownService();
    content = content.html();
    let markdown = turndownService.turndown(content ? content : "");
    for (let i = 0; i < handlers.length; i++) {
      markdown = handlers[i].resolveMarkdown(markdown);
    }
    return {
      title,
      content: markdown,
      tag,
    };
  },
};
